package com.gz.mylife.im;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import net.tsz.afinal.FinalDb;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.zl.smartmall.library.account.IAuth;
import android.content.Context;
import android.text.TextUtils;

public class SessionDao{

	private static final String TAG = "SessionDao";
	public static final int LIMIT = 20;
//	private static final String QUERY_NEXT_SEQ = "select id,pmid from tb_session_seq where id < %d order by id desc limit %d";
//	private static final String HAS_NEXT_SEQ = "id < %d order by id desc limit %d";
	
	
	public static SessionBean adapter4jpush(JSONObject data){
		SessionBean session = null;
		try{
			session = new SessionBean();
			session.setMsgid(data.getInt("i")); 
			session.setPmid(data.getInt("m"));
			session.setDateline(data.getLong("d"));
			
			// 发送人信息
			session.setFuid(data.getInt("u"));
			session.setFace(data.getString("f"));
			session.setGender(data.getInt("g"));
			session.setNickname(data.getString("n"));
			String c = data.getString("c");
			if(TextUtils.isEmpty(c)){
				c = session.getNickname()+"发了一张图片";
			}
			session.setContent(c);
			session.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
			
		}catch(JSONException e){
			e.printStackTrace();
		}
		return session;
	}
	
	public static SessionBean adapter(JSONObject data,int currUid){
		SessionBean bean = null;
		try{
			bean = new SessionBean();
			bean.setMsgid(data.getInt("msgid"));
			bean.setPmid(data.getInt("pmid"));
			bean.setFunreadnum(data.getInt("funreadnum"));
			bean.setDateline(data.getLong("dateline"));
			bean.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
			String content = data.getString("content");
			if(currUid == data.getInt("uid")){
				bean.setFuid(data.getInt("fuid"));
				bean.setNickname(data.getString("f_nickname"));
				bean.setFace(data.getString("f_face"));
				bean.setGender(data.getInt("f_gender"));
				
				if(TextUtils.isEmpty(content)){
					content = data.getString("nickname")+"发了一张图片";
				}
				bean.setContent(content);
			} else {
				bean.setFuid(data.getInt("uid"));
				bean.setNickname(data.getString("nickname"));
				bean.setFace(data.getString("face"));
				bean.setGender(data.getInt("gender"));
//				String content = data.getString("content");
				if(TextUtils.isEmpty(content)){
					content = data.getString("f_nickname")+"发了一张图片";
				}
				bean.setContent(content);
			}
//			String content = data.getString("content");
//			if(TextUtils.isEmpty(content)){
//				content = bean.getNickname()+"发了一张图片";
//			}
			bean.setContent(content);
		}catch(JSONException e){
			e.printStackTrace();
		}
		return bean;
	}
	
	public static SessionBean adapterFollow4Jpush(JSONObject data){
		SessionBean bean = null;
		try{
			bean = new SessionBean();
			bean.setPmid(SessionBean.PMID_FOLLOW);
			bean.setMsgid(data.getInt("i"));
			bean.setFuid(data.getInt("u"));       // UID
			bean.setNickname("朋友关注");
			bean.setGender(data.getInt("g"));
			bean.setFace(data.getString("f")); //头像
			bean.setDateline(data.getLong("d"));
			bean.setContent(data.getString("n")+"关注了你");
			bean.setUnreadCount(1);
			bean.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
		}catch(JSONException e){
			e.printStackTrace();
		}
		return bean;
	}
	
	public static SessionBean adapterComment4Jpush(JSONObject data){
		SessionBean bean = null;
		try{
			bean = new SessionBean();
			bean.setPmid(SessionBean.PMID_COMMENT);
			bean.setMsgid(data.getInt("i"));
			bean.setFuid(data.getInt("u"));       // UID
			bean.setNickname("有新回帖");
			bean.setGender(data.getInt("g"));
			bean.setFace(data.getString("f")); //头像
			bean.setDateline(data.getLong("d"));
			bean.setContent(data.getString("n")+"回复了你的帖子");
			bean.setUnreadCount(1);
			bean.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
		}catch(JSONException e){
			e.printStackTrace();
		}
		return bean;
	}
	
	public static void update(Context cxt,SessionBean bean){
		FinalDb.create(cxt).update(bean);
	}
	
	public static void updateShowStatus(Context cxt,SessionBean bean){
		FinalDb.create(cxt).update(bean, "pmid="+bean.getPmid()+" and "+"currentUID=" + IAuth.getInstance().loadUserInfo().getUid());
	}
	
	public static List<SessionBean> adapter(JSONArray array){
		int uid = IAuth.getInstance().loadUserInfo().getUid();
		int len = array.length();
		List<SessionBean> beans = new ArrayList<SessionBean>(len);
		for (int i = 0; i < len; i++) {
			try {
				SessionBean bean = adapter(array.getJSONObject(i), uid);
				beans.add(bean);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return beans;
	}
	
	
	
	public static SessionBean findSession(Context cxt ,int fuid){
		return FinalDb.create(cxt).getUnique(SessionBean.class, "fuid="+fuid+" and pmid > 0"+" and "+"currentUID=" + IAuth.getInstance().loadUserInfo().getUid());
	}

	public static List<SessionBean> findSessionByLimit(Context cxt,int row){
		FinalDb finalDb = FinalDb.create(cxt);
		List<SessionBean> sessions = finalDb.findAllByWhere(SessionBean.class, "pmid!="+SessionBean.PMID_COMMENT+" and "+"pmid!="+SessionBean.PMID_FOLLOW+" and "+"currentUID="+ IAuth.getInstance().loadUserInfo().getUid(), "dateline desc limit "+row+","+LIMIT);
		return sessions;
	}
	public static List<SessionBean> findSessionFirstByLimit(Context cxt,int row){
		FinalDb finalDb = FinalDb.create(cxt);
		List<SessionBean> lists = new ArrayList<SessionBean>();
		List<SessionBean> sessions1 = finalDb.findAllByWhere(SessionBean.class, "showStatus==0"+" and "+"pmid=="+SessionBean.PMID_COMMENT+" and "+"currentUID="+IAuth.getInstance().loadUserInfo().getUid()+" or "+"pmid=="+SessionBean.PMID_FOLLOW, "dateline desc limit "+row+","+LIMIT);
		if(sessions1 != null){
			lists.addAll(sessions1);
		}
		List<SessionBean> sessions2 = finalDb.findAllByWhere(SessionBean.class, "showStatus==0"+" and "+"pmid!="+SessionBean.PMID_COMMENT+" and "+"pmid!="+SessionBean.PMID_FOLLOW+" and "+"currentUID="+IAuth.getInstance().loadUserInfo().getUid(), "dateline desc limit "+row+","+LIMIT);
		if(sessions2 != null){
			lists.addAll(sessions2);
		}
		return lists;
	}
	
	public static boolean hasNext(Context cxt,long dateline){
		FinalDb finalDb = FinalDb.create(cxt);
		return finalDb.getCount(SessionBean.class, "dateline <"+dateline+" and "+"currentUID="+IAuth.getInstance().loadUserInfo().getUid()+" ORDER BY dateline desc") > 0;
	}
	
	
	public static void save(Context cxt,List<SessionBean> sessions){
		FinalDb finalDb = FinalDb.create(cxt);
		finalDb.deleteByWhere(SessionBean.class, "pmid!="+SessionBean.PMID_COMMENT+" and "+"pmid!="+SessionBean.PMID_FOLLOW+" and "+"currentUID="+IAuth.getInstance().loadUserInfo().getUid());
		finalDb.batchSave(sessions);
	}
	
	public static void save(Context cxt,SessionBean session){
		if(session == null)
			return;
		FinalDb finalDb = FinalDb.create(cxt);
		finalDb.deleteByWhere(SessionBean.class, "pmid="+session.getPmid()+" and "+"currentUID="+IAuth.getInstance().loadUserInfo().getUid());
		finalDb.saveBindId(session);
	}
	/*
	 * 查询聊天记录pmid代表聊天记录
	 */
	public static int getSessionUnreadCount(Context cxt,SessionBean session){
		if(session == null)
			return 0;
		FinalDb finalDb = FinalDb.create(cxt);
		SessionBean bean = finalDb.getUnique(SessionBean.class, "pmid="+session.getPmid()+" and "+"currentUID="+IAuth.getInstance().loadUserInfo().getUid());
		if(bean == null){
			return 0;
		}
		return bean.getUnreadCount();
	}
	/**
	 * 获取本条会话在本地的记录
	 * @param cxt
	 * @param session
	 * @return
	 */
	public static SessionBean getSession(Context cxt,SessionBean session){
		if(session == null)
			return null;
		FinalDb finalDb = FinalDb.create(cxt);
		SessionBean bean = finalDb.getUnique(SessionBean.class, "pmid="+session.getPmid()+" and "+"currentUID="+IAuth.getInstance().loadUserInfo().getUid());
		return bean;
	}
	/*
	 * 查询回帖的记录
	 */
	public static int getCommentSessionUnreadCount(Context cxt,SessionBean session){
		if(session == null)
			return 0;
		FinalDb finalDb = FinalDb.create(cxt);
		SessionBean bean = finalDb.getUnique(SessionBean.class, "pmid="+session.getPmid()+" and fuid="+session.getFuid()+" and "+"currentUID="+IAuth.getInstance().loadUserInfo().getUid());
		if(bean == null){
			return 0;
		}
		return bean.getUnreadCount();
	}
	
	static class MyComparator implements Comparator<HashMap<String, Object>> {
		@Override
		public int compare(HashMap<String, Object> o1,
				HashMap<String, Object> o2) {
			long t1 = toLong(o1.get("dateline"), 0L);
			long t2 = toLong(o2.get("dateline"), 0L);
			// 降序
			if (t1 > t2) {
				return 1;
			} else if (t1 == t2) {
				return 0;
			} else {
				return -1;
			}
		}
	}
	
	/**
	 * 1 拷贝到2
	 * @param arg0
	 * @param arg1
	 */
	public static void copyProperty(SessionBean arg0, SessionBean arg1){
		
	}
    
	public static long toLong(Object value,long defaultValue){
		if(value == null)
			return defaultValue;
		try{
			if(value instanceof Long){
				defaultValue = (Long) value;
			} else {
				Long l = ConvertUtils.convert(value.toString(), Long.class);
				if(l != null){
					defaultValue = l;
				}
			}
		}catch(Exception e){
		}
		return defaultValue;
	}
	
}
